package com.lv.suyiyong.hfr.fragment

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.SizeUtils
import com.lv.common.base.BaseFragment
import com.lv.common.bean.CommonSelectedBean
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.AnimationUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.MyUtils
import com.lv.common.utils.showToast
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.service.bean.CompanyBean
import com.lv.service.bean.ProvinceCityBean
import com.lv.service.dialog.AddressLRTopPopupView
import com.lv.service.dialog.SelectedShopTopGridPopupView
import com.lv.service.dialog.SelectedSingleTopGridPopupView
import com.lv.service.model.EditorViewModel
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.SearchPageBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.room.address.LocationNewReceiptAddressDbHelper
import com.lv.service.room.address.ReceiptAddressItem
import com.lv.service.room.company.CompanyItemBean
import com.lv.service.utils.YgxToolsKt
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.FactoryAdapter
import com.lv.suyiyong.hfr.databinding.FragmentHomeSearchFactoryBinding
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.enums.PopupPosition
import com.lxj.xpopup.interfaces.XPopupCallback
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/3/10 3:49 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述： NewTemplate 1 公司首页 黑色模板
 */
class HomeSearchFactoryFragment : BaseFragment(), OnClickListener {
    private var page: Int = 1
    private var pageSize: Int = Constants.pageSize
    private var mBeans = mutableListOf<CompanyItemBean>()
    private var mAddressBeans = mutableListOf<ReceiptAddressItem>()
    private var mSpecially = mutableListOf<String>()
    private var mOrderByBeans = mutableListOf<CommonSelectedBean>()
    private var mZZBeans = mutableListOf<CommonSelectedBean>()
    private var mLocationBeans = mutableListOf<ProvinceCityBean>()
//    private val mParamsMap = mutableMapOf<String, String>()
    private var mAdapter: FactoryAdapter? = null
    private var mTab = 0
    private var mName = ""
    private var mOrderBy = "0"
    private var mLogin = false
    private var mFristLoading = true
    private val mEditorViewModel: EditorViewModel by activityViewModels()
    private val viewModelService: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private var mBinding: FragmentHomeSearchFactoryBinding? = null

    override fun getLayoutRes() = R.layout.fragment_home_search_factory

    override fun bindView(view: View, savedInstanceState: Bundle?): ViewDataBinding {
        mBinding = FragmentHomeSearchFactoryBinding.bind(view).apply {
            initSingleClickListener(viewZh, tvSaler, viewLocation, viewZz)
        }
        return mBinding!!
    }


    override fun initConfig() {
        super.initConfig()
        if (mFristLoading) {
            mFristLoading = false
//            searchPage()
        }
        lifecycleScope.launch {
            val taskAddress = async {
                val mAllAddress = getAddressForDB()
                val list = mAllAddress?.let { YgxToolsKt.fourSelectedAddAllToCity(it, "所有地区") }
                mAddressBeans.clear()
                list?.let { mAddressBeans.addAll(it) }
            }
            taskAddress.await()
            initPage()
        }

    }

    private fun initPage() {
        mSpecially.clear()
        mOrderByBeans.clear()
        mOrderByBeans.add(CommonSelectedBean("回头率", "1"))
        mOrderByBeans.add(CommonSelectedBean("店铺信用分", "2"))
        mOrderByBeans.add(CommonSelectedBean("综合排序", "0", true))
        mZZBeans.clear()
        mZZBeans.add(CommonSelectedBean("金牌店铺", "2"))
        mZZBeans.add(CommonSelectedBean("认证店铺", "1"))
        mZZBeans.add(CommonSelectedBean("全部店铺", "0", true))

        initAdapter()

        mEditorViewModel.obCommon.observe(this) {
            val id = it.id
            val tag = it.tag
            if (tag == mTab) {
                if (id.isNullOrEmpty()) {
                    showToast("请输入要搜索的商品/门店")
                    mBeans.clear()
                    mAdapter?.removeEmptyView()
                    mAdapter?.notifyDataSetChanged()
                } else if (id != mName) {
                    mName = id
                    mBinding?.refreshLayout?.autoRefresh()
                }
            }
        }
    }

    private suspend fun getAddressForDB(): List<ReceiptAddressItem>? {
        return withContext(Dispatchers.IO) {
            //所有城市
            LocationNewReceiptAddressDbHelper.getAllLocationSuspend(requireContext())
        }
    }

    private fun initAdapter() {
        mAdapter = FactoryAdapter(mBeans)
        mBinding?.rvContent?.adapter = mAdapter
        mBinding?.rvContent?.addItemDecoration(
            SpacesItemDecoration(
                SizeUtils.dp2px(10.0f), SizeUtils.dp2px(10.0f), false
            )
        )

    }

    override fun initData() {
        super.initData()
        arguments?.let {
            mTab = it.getInt("tab", 0)
        }
        if (mTab == 3) {
            mBinding?.viewLocationBottom?.visibility = View.GONE
            mBinding?.tvLocation?.visibility = View.GONE
            mBinding?.ivArrowLocation?.visibility = View.GONE
            mBinding?.viewLocation?.visibility = View.GONE
        }

    }

    private fun setSearchTab(tab: Int) {
        when (tab) {
            0 -> {
                mBinding?.ivArrowZh?.LoadSrc(com.lv.common.R.drawable.icon_arrow_down_blue)
                mBinding?.tvZh?.setTextColor(Color.parseColor("#026DFF"))
                mBinding?.tvSaler?.setTextColor(Color.parseColor("#242424"))
                mBinding?.tvLocation?.setTextColor(Color.parseColor("#242424"))
                mBinding?.ivArrowLocation?.LoadSrc(com.lv.common.R.drawable.icon_arrow_down_balck)
                mBinding?.tvZz?.setTextColor(Color.parseColor("#242424"))
                mBinding?.ivArrowZz?.LoadSrc(com.lv.common.R.drawable.icon_arrow_down_balck)

                mZZBeans.forEach { it.selected = false }
                mZZBeans[2].selected = true
                mBinding?.tvZz?.text = "企业资质"
            }

            1 -> {
                mBinding?.tvSaler?.setTextColor(Color.parseColor("#026DFF"))
                mBinding?.tvZh?.setTextColor(Color.parseColor("#242424"))
                mBinding?.ivArrowZh?.LoadSrc(com.lv.common.R.drawable.icon_arrow_down_balck)
                mBinding?.tvLocation?.setTextColor(Color.parseColor("#242424"))
                mBinding?.ivArrowLocation?.LoadSrc(com.lv.common.R.drawable.icon_arrow_down_balck)
                mBinding?.tvZz?.setTextColor(Color.parseColor("#242424"))
                mBinding?.ivArrowZz?.LoadSrc(com.lv.common.R.drawable.icon_arrow_down_balck)

                mOrderByBeans.forEach { it.selected = false }
                mOrderByBeans[2].selected = true
                mBinding?.tvZh?.text = "综合排序"
                mZZBeans.forEach { it.selected = false }
                mZZBeans[2].selected = true
                mBinding?.tvZz?.text = "企业资质"
            }

            2 -> {
                mBinding?.tvSaler?.setTextColor(Color.parseColor("#242424"))
                mBinding?.tvZh?.setTextColor(Color.parseColor("#242424"))
                mBinding?.ivArrowZh?.LoadSrc(com.lv.common.R.drawable.icon_arrow_down_balck)
                mBinding?.tvLocation?.setTextColor(Color.parseColor("#026DFF"))
                mBinding?.ivArrowLocation?.LoadSrc(com.lv.common.R.drawable.icon_arrow_down_blue)
                mBinding?.tvZz?.setTextColor(Color.parseColor("#242424"))
                mBinding?.ivArrowZz?.LoadSrc(com.lv.common.R.drawable.icon_arrow_down_balck)
                mOrderBy = "0"
                mOrderByBeans.forEach { it.selected = false }
                mOrderByBeans[2].selected = true
                mBinding?.tvZh?.text = "综合排序"
                mZZBeans.forEach { it.selected = false }
                mZZBeans[2].selected = true
                mBinding?.tvZz?.text = "企业资质"
            }

            3 -> {
                mBinding?.tvSaler?.setTextColor(Color.parseColor("#242424"))
                mBinding?.tvZh?.setTextColor(Color.parseColor("#242424"))
                mBinding?.ivArrowZh?.LoadSrc(com.lv.common.R.drawable.icon_arrow_down_balck)
                mBinding?.tvLocation?.setTextColor(Color.parseColor("#242424"))
                mBinding?.ivArrowLocation?.LoadSrc(com.lv.common.R.drawable.icon_arrow_down_balck)
                mBinding?.tvZz?.setTextColor(Color.parseColor("#026DFF"))
                mBinding?.ivArrowZz?.LoadSrc(com.lv.common.R.drawable.icon_arrow_down_blue)
                mOrderBy = "0"
                mOrderByBeans.forEach { it.selected = false }
                mOrderByBeans[2].selected = true
                mBinding?.tvZh?.text = "综合排序"

            }
        }
    }

    private fun showOrderSelected() {
        setSearchTab(0)

        val mPopupView =
            SelectedSingleTopGridPopupView(
                requireContext(), mOrderByBeans,
            ) { current, data ->
//                mOrderByBeans.clear()
//                mOrderByBeans.addAll(data)
                if (current != -1) {
                    val tag = mOrderByBeans[current].tag
                    if (mOrderBy != tag) {
                        val name = mOrderByBeans[current].name
                        mOrderBy = tag
                        mBinding?.tvZh?.text = name
                        mBinding?.refreshLayout?.autoRefresh()
                    }
                }
            }

        XPopup.Builder(requireContext())
            .setPopupCallback(object : XPopupCallback {
                override fun onCreated(popupView: BasePopupView?) {

                }

                override fun beforeShow(popupView: BasePopupView?) {
                    AnimationUtils.animationIvOpen(mBinding?.ivArrowZh)
                    mBinding?.viewZhBottom?.visibility = View.VISIBLE
                }

                override fun onShow(popupView: BasePopupView?) {
                }

                override fun onDismiss(popupView: BasePopupView?) {
                }

                override fun beforeDismiss(popupView: BasePopupView?) {
                    AnimationUtils.animationIvClose(mBinding?.ivArrowZh)
                    mBinding?.viewZhBottom?.visibility = View.GONE
                }

                override fun onBackPressed(popupView: BasePopupView?): Boolean {
                    return false
                }

                override fun onKeyBoardStateChanged(popupView: BasePopupView?, height: Int) {
                }

                override fun onDrag(
                    popupView: BasePopupView?,
                    value: Int,
                    percent: Float,
                    upOrLeft: Boolean
                ) {
                }

                override fun onClickOutside(popupView: BasePopupView?) {
                }
            })
            .atView(mBinding?.clTop)
            .isViewMode(true)
            .popupPosition(PopupPosition.Bottom)
            .asCustom(mPopupView)
            .show()


    }

    override fun onClick(v: View?) {
        when (v?.id) {

            R.id.view_zh -> {
                mLocationBeans.clear()
                showOrderSelected()
            }

            R.id.tv_saler -> {
                if (mOrderBy == "3") {
                    return
                }
                mOrderBy = "3"
                mLocationBeans.clear()
                setSearchTab(1)
                mBinding?.refreshLayout?.autoRefresh()
            }

            R.id.view_location -> showLocationSelected()
            R.id.view_zz -> {
                mLocationBeans.clear()
                showZzSelected()
            }

        }
    }

    private fun showZzSelected() {
        setSearchTab(3)
        val mPopupView =
            SelectedShopTopGridPopupView(
                requireContext(), mZZBeans,
            ) { current, data ->
                val mSptem = mutableListOf<String>()
                for (i in 0 until mZZBeans.size) {
                    val selected = mZZBeans[i].selected
                    if (selected) {
                        val tag = mZZBeans[i].tag
                        when (tag) {
                            "0" -> {
                                mSptem.add("1")
                                mSptem.add("2")
                            }

                            else -> {
                                mSptem.add(tag)
                            }
                        }
                    }
                }
                if (mSptem != mSpecially) {
                    mSpecially.clear()
                    mSpecially.addAll(mSptem)
                    mBinding?.refreshLayout?.autoRefresh()
                }
                val list = mZZBeans.filter { it.selected }
                if (list.isEmpty()) {
                    mBinding?.tvZz?.text = "企业资质"
                } else {
                    val list0 = list.filter { it.tag == "0" }
                    if (list0.isEmpty()) {
                        val list1 = list.filter { it.tag == "1" }
                        val list2 = list.filter { it.tag == "2" }
                        if (list1.isNotEmpty() && list2.isNotEmpty()) {
                            mBinding?.tvZz?.text = "全部店铺"
                            mZZBeans[0].selected = false
                            mZZBeans[1].selected = false
                            mZZBeans[2].selected = true
                        } else if (list1.isNotEmpty()) {
                            mBinding?.tvZz?.text = "认证店铺"
                        } else {
                            mBinding?.tvZz?.text = "金牌店铺"
                        }
                    } else {
                        mBinding?.tvZz?.text = "全部店铺"
                    }
                }
            }

        XPopup.Builder(requireContext())
            .setPopupCallback(object : XPopupCallback {
                override fun onCreated(popupView: BasePopupView?) {

                }

                override fun beforeShow(popupView: BasePopupView?) {
                    AnimationUtils.animationIvOpen(mBinding?.ivArrowZz)
                    mBinding?.viewZzBottom?.visibility = View.VISIBLE
                }

                override fun onShow(popupView: BasePopupView?) {
                }

                override fun onDismiss(popupView: BasePopupView?) {
                }

                override fun beforeDismiss(popupView: BasePopupView?) {
                    AnimationUtils.animationIvClose(mBinding?.ivArrowZz)
                    mBinding?.viewZzBottom?.visibility = View.GONE
                }

                override fun onBackPressed(popupView: BasePopupView?): Boolean {
                    return false
                }

                override fun onKeyBoardStateChanged(popupView: BasePopupView?, height: Int) {
                }

                override fun onDrag(
                    popupView: BasePopupView?,
                    value: Int,
                    percent: Float,
                    upOrLeft: Boolean
                ) {
                }

                override fun onClickOutside(popupView: BasePopupView?) {
                }
            })
            .atView(mBinding?.clTop)
            .isViewMode(true)
            .popupPosition(PopupPosition.Bottom)
            .asCustom(mPopupView)
            .show()
    }

    private fun showLocationSelected() {
        setSearchTab(2)
        val mPopupView =
            AddressLRTopPopupView(
                requireContext(), mAddressBeans,
            ) { current, data ->
                when (current) {
                    0 -> {
                        mLocationBeans.clear()
                        data?.forEach {
                            if (it.isShow) {
                                val citys = mutableListOf<String>()
                                it.telSecondCategories?.forEachIndexed { index, telSecondCategoryBean ->
                                    if (telSecondCategoryBean.isShow && index != 0) {
                                        citys.add(telSecondCategoryBean.name ?: "")
                                    }
                                }
                                mLocationBeans.add(ProvinceCityBean(it.name, citys))
                            }
                        }
                        mBinding?.refreshLayout?.autoRefresh()
                    }
                }

            }

        XPopup.Builder(requireContext())
            .setPopupCallback(object : XPopupCallback {
                override fun onCreated(popupView: BasePopupView?) {

                }

                override fun beforeShow(popupView: BasePopupView?) {
                    AnimationUtils.animationIvOpen(mBinding?.ivArrowLocation)
                    mBinding?.viewLocationBottom?.visibility = View.VISIBLE
                }

                override fun onShow(popupView: BasePopupView?) {
                }

                override fun onDismiss(popupView: BasePopupView?) {
                }

                override fun beforeDismiss(popupView: BasePopupView?) {
                    AnimationUtils.animationIvClose(mBinding?.ivArrowLocation)
                    mBinding?.viewLocationBottom?.visibility = View.GONE
                }

                override fun onBackPressed(popupView: BasePopupView?): Boolean {
                    return false
                }

                override fun onKeyBoardStateChanged(popupView: BasePopupView?, height: Int) {
                }

                override fun onDrag(
                    popupView: BasePopupView?,
                    value: Int,
                    percent: Float,
                    upOrLeft: Boolean
                ) {
                }

                override fun onClickOutside(popupView: BasePopupView?) {
                }
            })
            .atView(mBinding?.clTop)
            .isViewMode(true)
            .popupPosition(PopupPosition.Bottom)
            .asCustom(mPopupView)
            .show()
    }


    private fun searchPage() {
        val body =
            SearchPageBody(
                page, pageSize, "$mTab", mName, mOrderBy, mSpecially, mLocationBeans
            )
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                withContext(myScope.coroutineContext) {
                    viewModelService.searchPage(body)
                }
            parseResult(result)
        }
    }

    private fun parseResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<CompanyBean> { code, data, message, result ->
                val items = data?.items
                MyUtils.recyclerviewSetData(
                    page, pageSize, mBinding?.refreshLayout, mBeans, items, mAdapter
                )
                if (mBeans.isEmpty()) {
                    mAdapter?.setEmptyView(getEmptyView(mBinding?.rvContent!!))
                }

            }
            onBizError<CompanyBean> { code, message, data ->
                loadFinished()
                mBinding?.refreshLayout?.finishRefresh()
                mBinding?.refreshLayout?.finishLoadMore()
            }
        }
        data.onFailure {
            loadFinished()
            mBinding?.refreshLayout?.finishRefresh()
            mBinding?.refreshLayout?.finishLoadMore()
        }
    }

    override fun initEvents() {
        super.initEvents()
        mBinding?.refreshLayout?.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                searchPage()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                searchPage()
            }
        })

    }

    override fun onResume() {
        super.onResume()
    }


    companion object {
        fun newInstance(tab: Int): HomeSearchFactoryFragment {
            val args = Bundle()
            args.putInt("tab", tab)

            val fragment = HomeSearchFactoryFragment()
            fragment.arguments = args
            return fragment
        }
    }


}